package com.guojiang.guopicturebackend.controller;


import cn.hutool.core.util.ObjUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.guojiang.guopicturebackend.annotation.AuthCheck;
import com.guojiang.guopicturebackend.common.BaseResponse;
import com.guojiang.guopicturebackend.common.DeleteRequest;
import com.guojiang.guopicturebackend.common.ResultUtils;
import com.guojiang.guopicturebackend.constant.UserConstant;
import com.guojiang.guopicturebackend.exception.ErrorCode;
import com.guojiang.guopicturebackend.exception.ThrowUtils;
import com.guojiang.guopicturebackend.manager.auth.SpaceUserAuthManager;
import com.guojiang.guopicturebackend.model.dto.picture.PictureQueryRequest;
import com.guojiang.guopicturebackend.model.dto.space.*;
import com.guojiang.guopicturebackend.model.entity.Picture;
import com.guojiang.guopicturebackend.model.entity.Space;
import com.guojiang.guopicturebackend.model.entity.User;
import com.guojiang.guopicturebackend.model.enums.SpaceLevelEnum;
import com.guojiang.guopicturebackend.model.enums.SpaceTypeEnum;
import com.guojiang.guopicturebackend.model.vo.space.SpaceVO;
import com.guojiang.guopicturebackend.service.PictureService;
import com.guojiang.guopicturebackend.service.SpaceService;
import com.guojiang.guopicturebackend.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/space")
public class SpaceController {

    @Resource
    private UserService userService;

    @Resource
    private PictureService pictureService;

    @Resource
    private SpaceService spaceService;

    @Resource
    private TransactionTemplate transactionTemplate;

    @Resource
    private SpaceUserAuthManager spaceUserAuthManager;

    /**
     * 创建空间（用户本人）
     *
     * @param spaceAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addSpace(@RequestBody SpaceAddRequest spaceAddRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(spaceAddRequest == null, ErrorCode.PARAMS_ERROR, "spaceAddRequest 为空");
        User loginUser = userService.getLoginUser(request);
        long newSpaceId = spaceService.addSpace(spaceAddRequest, loginUser);
        return ResultUtils.success(newSpaceId);
    }

    /**
     * 删除空间（本人/管理员）
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteSpace(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        Long deleteSpaceId = deleteRequest.getId();
        // 校验请求体是否正常
        ThrowUtils.throwIf(deleteRequest == null || deleteSpaceId <= 0, ErrorCode.PARAMS_ERROR, "deleteRequest 为空");
        User loginUser = userService.getLoginUser(request);
        // 校验要删除的数据是否存在
        Space deleteSpace = spaceService.getById(deleteSpaceId);
        ThrowUtils.throwIf(deleteSpace == null, ErrorCode.NOT_FOUND_ERROR, "要删除的空间不存在");
        // 仅本人或者管理员可以删除空间
        ThrowUtils.throwIf(!deleteSpace.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)
                , ErrorCode.NO_AUTH_ERROR, "无权删除该空间");
        // 开启事务
        transactionTemplate.execute(status -> {
            // 先查询空间关联的图片
            ArrayList<Long> deletePictureIds = new ArrayList<>();
            List<Picture> deletePicture = pictureService.lambdaQuery().eq(Picture::getSpaceId, deleteSpaceId).list();
            for (Picture picture : deletePicture) {
                deletePictureIds.add(picture.getId());
            }
            // 操作数据库批量删除关联空间的图片
            boolean removeBatchByIdsResult = pictureService.removeBatchByIds(deletePictureIds);
            ThrowUtils.throwIf(!removeBatchByIdsResult, ErrorCode.OPERATION_ERROR, "删除空间关联图片失败，系统错误");
            // 操作数据库删除空间
            boolean removeSpaceResult = spaceService.removeById(deleteSpaceId);
            ThrowUtils.throwIf(!removeSpaceResult, ErrorCode.OPERATION_ERROR, "删除空间失败，系统错误");
            return true;
        });
        return ResultUtils.success(true);
    }

    /**
     * 更新空间（仅管理员可用）
     *
     * @param spaceUpdateRequest
     * @param request
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateSpace(@RequestBody SpaceUpdateRequest spaceUpdateRequest, HttpServletRequest request) {
        Long updateSpaceId = spaceUpdateRequest.getId();
        // 判断更新请求体是否正常
        ThrowUtils.throwIf(spaceUpdateRequest == null || updateSpaceId <= 0
                , ErrorCode.PARAMS_ERROR);
        // 判断要更新的空间是否存在，不存在无需更新
        Space updateSpace = spaceService.getById(updateSpaceId);
        ThrowUtils.throwIf(ObjUtil.isNull(updateSpace), ErrorCode.NOT_FOUND_ERROR, "要更新的空间不存在");
        // 将实体类和 DTO 进行转换  
        Space space = new Space();
        BeanUtils.copyProperties(spaceUpdateRequest, space);
        // 设置更新时间
        space.setUpdateTime(new Date());
        // 自动填充空间级别数据
        spaceService.fillSpaceBySpaceLevel(space);
        // 空间合法性校验
        spaceService.validSpace(space);
        // 操作数据库  
        boolean updateResult = spaceService.updateById(space);
        ThrowUtils.throwIf(!updateResult, ErrorCode.OPERATION_ERROR, "更新失败，系统错误");
        return ResultUtils.success(true);
    }

    /**
     * 根据 id 获取空间（仅管理员可用）
     *
     * @param id
     * @return
     */
    @GetMapping("/get")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Space> getSpaceById(Long id) {
        ThrowUtils.throwIf(id == null, ErrorCode.PARAMS_ERROR, "请求参数为空");
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR, "参数非法");
        // 查询数据库  
        Space space = spaceService.getById(id);
        ThrowUtils.throwIf(ObjUtil.isNull(space), ErrorCode.NOT_FOUND_ERROR, "要获取的空间不存在");
        return ResultUtils.success(space);
    }

    /**
     * 根据 id 获取空间视图（仅管理员和创建空间的用户本人可以查看）
     *
     * @param id
     * @param request
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<SpaceVO> getSpaceVOById(Long id, HttpServletRequest request) {
        // 用户未登录，无法根据 id 获取空间视图
        User loginUser = userService.getLoginUser(request);
        ThrowUtils.throwIf(loginUser == null, ErrorCode.OPERATION_ERROR, "请先登录");
        Long loginUserId = loginUser.getId();
        BaseResponse<Space> spaceBaseResponse = this.getSpaceById(id);
        Space space = spaceBaseResponse.getData();
        // 如果是私有空间，仅管理员或空间创建者可以查看空间信息
        if (SpaceTypeEnum.PRIVATE.getValue() == space.getSpaceType()) {
            ThrowUtils.throwIf(!(userService.isAdmin(loginUser) || space.getUserId().equals(loginUserId))
                    , ErrorCode.NO_AUTH_ERROR, "无权查看空间信息");
        }
        List<String> permissionList = spaceUserAuthManager.getPermissionList(space, loginUser);
        SpaceVO spaceVO = spaceService.getSpaceVO(space, request);
        spaceVO.setPermissionList(permissionList);
        return ResultUtils.success(spaceVO);
    }

    /**
     * 分页获取空间列表（仅管理员可用）
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Space>> listSpaceByPage(@RequestBody SpaceQueryRequest spaceQueryRequest) {
        long current = spaceQueryRequest.getCurrent();
        long size = spaceQueryRequest.getPageSize();
        // 查询数据库  
        Page<Space> spacePage = spaceService.page(new Page<>(current, size),
                spaceService.getQueryWrapper(spaceQueryRequest));
        return ResultUtils.success(spacePage);
    }

    /**
     * 分页获取空间视图（即使有这个功能，也要限制用户无法看到其他用户空间内部的信息）
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<SpaceVO>> listSpaceVOByPage(@RequestBody SpaceQueryRequest spaceQueryRequest,
                                                         HttpServletRequest request) {
        long current = spaceQueryRequest.getCurrent();
        long size = spaceQueryRequest.getPageSize();
        // 限制爬虫  
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库  
        Page<Space> spacePage = spaceService.page(new Page<>(current, size),
                spaceService.getQueryWrapper(spaceQueryRequest));
        // 获取封装类  
        return ResultUtils.success(spaceService.getSpaceVOPage(spacePage, request));
    }

    /**
     * 编辑空间（本人/管理员）
     *
     * @param spaceEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editSpace(@RequestBody SpaceEditRequest spaceEditRequest, HttpServletRequest request) {
        long editSpaceId = spaceEditRequest.getId();
        // 编辑请求体是否正常
        ThrowUtils.throwIf(spaceEditRequest == null || editSpaceId <= 0
                , ErrorCode.PARAMS_ERROR);
        // 判断要编辑的空间是否存在
        Space editSpace = spaceService.getById(editSpaceId);
        ThrowUtils.throwIf(ObjUtil.isNull(editSpace), ErrorCode.NOT_FOUND_ERROR, "要编辑的空间不存在");
        // 在此处将实体类和 DTO 进行转换  
        Space space = new Space();
        BeanUtils.copyProperties(spaceEditRequest, space);
        // 设置编辑时间  
        space.setEditTime(new Date());
        // 自动填充空间级别数据
        spaceService.fillSpaceBySpaceLevel(space);
        // 数据校验  
        spaceService.validSpace(space);
        User loginUser = userService.getLoginUser(request);
        // 仅本人或管理员可编辑
        ThrowUtils.throwIf(!(editSpace.getUserId().equals(loginUser.getId()) || userService.isAdmin(loginUser))
                , ErrorCode.NO_AUTH_ERROR, "无权编辑空间");
        // 操作数据库  
        boolean editResult = spaceService.updateById(space);
        ThrowUtils.throwIf(!editResult, ErrorCode.OPERATION_ERROR, "编辑空间失败，系统错误");
        return ResultUtils.success(true);
    }

    /**
     * 获取空间级别列表，便于前端展示
     *
     * @return
     */
    @GetMapping("/list/level")
    public BaseResponse<List<SpaceLevel>> listSpaceLevel() {
        List<SpaceLevel> spaceLevelList = Arrays.stream(SpaceLevelEnum.values())
                .map(spaceLevelEnum -> new SpaceLevel(
                        spaceLevelEnum.getValue(),
                        spaceLevelEnum.getText(),
                        spaceLevelEnum.getMaxCount(),
                        spaceLevelEnum.getMaxSize()
                )).collect(Collectors.toList());
        return ResultUtils.success(spaceLevelList);
    }
}